#include "PrimitiveDb.h"

namespace common {

PrimitiveDb::PrimitiveDb(PointDb* pointDb,ConstraintDb* constraintDb):DataBase<Primitive*> ("PrimitiveDb"),pointDb(pointDb),constraintDb(constraintDb) {

}
void PrimitiveDb::remove(int id) throw (MyException) {

	Primitive* prim = get(id);

	std::list<Point*> pnts = prim->getAllPoints();
	for (std::list<Point*>::iterator it = pnts.begin(); it != pnts.end(); it++) {
		if(constraintDb->getMaxId()>0){
			_keyType* constraintId = constraintDb->getIds();
			for(_keyType::iterator itc=constraintId->begin(); itc!= constraintId->end() ; itc++){
				Constraint* cn = constraintDb->get(*itc);
				if(cn->containsPoint(*it)){
					constraintDb->remove(cn->getId());
				}
			}
		}
		pointDb->remove((*it)->getId());
	}
	DataBase<Primitive*>::remove(id);

}
void PrimitiveDb::relax(){
	for(mapTypeIter it = data->begin();it!=data->end();it++){
		it->second->relax();
	}
}


Line* PrimitiveDb::addLine(Coordinate* c1, Coordinate* c2){
	//rejetrujemy punkty
	Point* p1 = pointDb->addPoint(c1);
	Point* p2 = pointDb->addPoint(c2);

	//wstaw do bazy nowa linie
	Line* l = new Line(getMaxId()+1,p1,p2);
	return dynamic_cast<Line*>(add(l));
}
Line* PrimitiveDb::addLine(Coordinate c1, Coordinate c2){
	//rejetrujemy punkty
	Point* p1 = pointDb->addPoint(c1);
	Point* p2 = pointDb->addPoint(c2);

	//wstaw do bazy nowa linie
	Line* l = new Line(getMaxId()+1,p1,p2);
	return dynamic_cast<Line*>(add(l));
}
Circle* PrimitiveDb::addCircle(Coordinate* c1,Coordinate* c2){
	//rejetrujemy punkty
	Point* p1 = pointDb->addPoint(c1);
	Point* p2 = pointDb->addPoint(c2);

	//wstaw do bazy nowa linie
	Circle* c = new Circle(getMaxId()+1,p1,p2);
	return dynamic_cast<Circle*>(add(c));
}
Circle* PrimitiveDb::addCircle(Coordinate c1,Coordinate c2){
	//rejetrujemy punkty
	Point* p1 = pointDb->addPoint(c1);
	Point* p2 = pointDb->addPoint(c2);

	//wstaw do bazy nowa linie
	Circle* c = new Circle(getMaxId()+1,p1,p2);
	return dynamic_cast<Circle*>(add(c));
}
Segment* PrimitiveDb::addSegment(std::list<Coordinate*> cSet){

	//rejetrujemy punkty
	std::list<Point*>* pointSet = new std::list<Point*>();
	std::list<Coordinate*>::reverse_iterator it;

	for(it=cSet.rbegin();it!=cSet.rend();it++){
		pointSet->push_back(pointDb->addPoint(**it));
	}
	Segment* s = new Segment(getMaxId()+1,*pointSet);
	return dynamic_cast<Segment*>(add(s));
}
Segment* PrimitiveDb::addSegment(std::list<Coordinate> cSet){
	//rejetrujemy punkty
	std::list<Point*>* pointSet = new std::list<Point*>();
	std::list<Coordinate>::iterator it;

	for(it=cSet.begin();it!=cSet.end();it++){
		pointSet->push_back(pointDb->addPoint(*it));
	}
	Segment* s = new Segment(getMaxId()+1,*pointSet);
	return dynamic_cast<Segment*>(add(s));
}

PrimitiveDb::~PrimitiveDb() {

}

}
